﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Data;
using System.ComponentModel;
using DoubleH.Utility;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;

namespace DoubleH
{
    public partial class WorkArea : Window
    {
        private void NewObj()
        {
            if (selectedMenu == null)
                return;

            selectedMenu.DataTable = null;
            pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, selectedMenu.Tag);
        }

        private void PreObj()
        {
            if (int.Parse(labelIndex1.Content.ToString()) == 1)
                return;

            uint start = uint.Parse(labelIndex1.Content.ToString()) - DoubleHConfig.UserConfig.GroupDataCount;
            labelIndex1.Content = start;
            labelIndex2.Content = (start - 1 + DoubleHConfig.UserConfig.GroupDataCount);
            BeginBindData();
        }

        private void NextObj()
        {
            int count = uCPagePanel1.Items.Count;
            if (count < DoubleHConfig.UserConfig.GroupDataCount)//如果列表已经没有项目就别搜索了
                return;

            labelIndex1.Content = (int.Parse(labelIndex1.Content.ToString()) + DoubleHConfig.UserConfig.GroupDataCount);
            BeginBindData();
            labelIndex2.Content = (int.Parse(labelIndex2.Content.ToString()) + (count < DoubleHConfig.UserConfig.GroupDataCount ? count : (int)DoubleHConfig.UserConfig.GroupDataCount));
        }

        private void EditObj()
        {
            selectedMenu.DataTable = uCPagePanel1.SelectedItem as FCNS.Data.Table.DataTableS;
            pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, "Edit");
        }

        private void SearchObjByWindow()
        {
            if (selectedMenu == null)
                return;

            DoubleH.Utility.Search.WindowSearch so = new DoubleH.Utility.Search.WindowSearch();
            so.Init(selectedMenu);
            so.ShowDialog();
            if (so.Items != null)
                uCPagePanel1.LoadData(null, so.Items);
        }

        private void SearchObjByText()
        {
            if (selectedMenu == null)
                return;

            if (string.IsNullOrEmpty(textBoxSearch.Text))
            {
                BeginBindData();
                return;
            }

            StringBuilder sb = new StringBuilder();
            selectedMenu.UserParams.Items.ForEach(f =>
            {
                if (f.CanSearch)
                    sb.Append(f.BindingName + ",");
            });
            DoubleH.Utility.Search.SearchUtility su = new Utility.Search.SearchUtility();
            uCPagePanel1.LoadData(null, su.Search(uCPagePanel1.Items, textBoxSearch.Text, sb.ToString().Split(',')));
        }

        private void ExpanderOpen()
        {
            expanderMore.Cursor = Cursors.Hand;
            //expanderMore.Height = 196;
        }

        private void ExpanderClose()
        {
            expanderMore.Cursor = Cursors.Arrow;
            expanderMore.IsExpanded = false; 
            //expanderMore.Height = 25;
        }

        private void Print()
        {
            FCNS.Data.Interface.IOrder order = uCPagePanel1.SelectedItem as FCNS.Data.Interface.IOrder;
            if (order == null)
            {
                MessageWindow.Show("当前项目不支持打印");
                return;
            }

            PrintFunction.Print(uCPagePanel1.SelectedItem, selectedMenu.TableText);
        }

        private void PrintList()
        {
            uCPagePanel1.Mode = Utility.UC.UCPagePanel.EnumMode.列表;
            PrintFunction.PrintList(uCPagePanel1.DataGridObj,null, selectedMenu);
        }

        private void EventImport()
        {
            DoubleH.Utility.IO.FileTools ft = new FileTools();
            if (selectedMenu != null)
                ft.ImportFileToData(selectedMenu.TableName);
        }

        private void EventExport()
        {
            DoubleH.Utility.IO.FileTools ft = new FileTools();
            ft.ExportDataToFile(uCPagePanel1.Items, string.Empty);
        }

        private void EventZuoFei()
        {
            if (selectedMenu.Authority < Table.UserS.EnumAuthority.作废)
            {
                MessageWindow.Show("权限不足");
                return;
            }

            if (MessageWindow.Show("", "确定要作废选中项目吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            switch (selectedMenu.TableText)
            {
                case DataTableText.Pos禁售商品:
                    Table.ProductS ps = uCPagePanel1.SelectedItem as Table.ProductS;
                    if (ps != null)
                    {
                        ps.UpdatePosCanNotUseList(string.Empty);
                    }
                    break;

                default:
                    FCNS.Data.Interface.IDataTable table = uCPagePanel1.SelectedItem as FCNS.Data.Interface.IDataTable;
                    if (table != null)
                        MessageWindow.Show(table.ZuoFei().ToString());

                    break;
            }
            BeginBindData();
        }

        //private void EventZuoFei()
        //{
        //    if (MessageWindow.Show("", "确定要停用/作废选中项目吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
        //        return;

        //    if (selectedMenu.TableText == DataTableText.Pos禁售商品)
        //    {
        //        Table.ProductS ps = uCPagePanel1.SelectedItem as Table.ProductS;
        //        if (ps != null)
        //            ps.SetPosCanNotUseList(false);
        //    }
        //    else
        //    {
        //        int i = 0;
        //        foreach (object obj in uCPagePanel1.SelectedItems)
        //        {
        //            FCNS.Data.Interface.IDataTable table = obj as FCNS.Data.Interface.IDataTable;
        //            if (table != null)
        //                if (table.ZuoFei() == Table.DataTableS.EnumDatabaseStatus.操作成功)
        //                    continue;

        //            i++;
        //        }
        //        if (i != 0)
        //            MessageWindow.Show(i.ToString() + " 张单据存在业务来往,无法删除");
        //    }
        //}

        private void ExpanderConfigOpen()
        {
            expanderConfig.Cursor = Cursors.Hand;
            expanderConfig.Height = 131;
        }

        private void ExpanderConfigClose()
        {
            expanderConfig.Cursor = Cursors.Arrow; 
            expanderConfig.IsExpanded = false;
            expanderConfig.Height = 25;
        }

        private void OpenSysconfig()
        {
            pluginManager.LoadPlugin(DbDefine.baseDir + "SysConfig.dll", null, DataTableText.系统配置, null, null);
        }

        private void LoginOff()
        {
            ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);
            this.Hide();
            if (!NormalUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
            {
                System.Environment.Exit(0);
                return;
            }
            else
            {
                InitUserVar();
                this.Show();
            }
        }

        private void OpenHelp()
        {
            AboutMe am = new AboutMe();
            am.ShowDialog();
        }

        private void OpenCalc()
        {
            System.Diagnostics.Process.Start("calc.exe");
        }




        private void PagePanelSizeChanged()
        {
            Thickness tk = expanderMore.Margin;
            expanderMore.Margin = new Thickness((this.Width - 450) / 2 + 270, tk.Top, tk.Right, tk.Bottom);
        }

        private void PagePanelItemClick(DataGridCellInfo cell)
        {//alert 要优化
            if (selectedMenu == null||cell==null)
                return;

            if (selectedMenu.TableText != DataTableText.采购物流跟踪 &&
                selectedMenu.TableText != DataTableText.批发物流跟踪 &&
                selectedMenu.TableText != DataTableText.仓库物流跟踪) 
                return;

            if(cell.Column!=null&& cell.Column.Header.ToString() == "状态")
            {
                Table.WuLiuS ws = cell.Item as Table.WuLiuS;
                if (ws != null)
                    Process.Start(ws._Http);
            }
        }

        private void PagePanelItemDoubleClick()
        {
                switch (selectedMenu.TableText)
                {
                    case DataTableText.Pos机器号:
                        Table.PosS pos = uCPagePanel1.SelectedItem as Table.PosS;
                        switch (pos.Enable)
                        {
                            case Table.PosS.EnumEnable.启用:
                                if (MessageWindow.Show("", "确定要停用 " + pos.PosNO  + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.UpdateTo(Table.PosS.EnumEnable.停用);
                                break;
                            case Table.PosS.EnumEnable.评估:
                                if (MessageWindow.Show("", "确定要审核 " + pos.PosNO + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.UpdateTo(Table.PosS.EnumEnable.启用);
                                break;
                            case Table.PosS.EnumEnable.停用:
                                if (MessageWindow.Show("", "确定要启用 " + pos.PosNO  + " 吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                    pos.UpdateTo(Table.PosS.EnumEnable.启用);
                                break;
                        }
                        break;

                    default:
                        selectedMenu.DataTable = uCPagePanel1.SelectedItem as FCNS.Data.Table.DataTableS;
                        pluginManager.LoadPlugin(DbDefine.baseDir + selectedMenu.DllFile, null, selectedMenu.TableText, selectedMenu.DataTable, selectedMenu.Tag);
                        break;
                }
            }

        private void PagePanelModeChanged(Utility.UC.UCPagePanel.EnumMode ee)
        {
            if (selectedMenu != null)
                selectedMenu.UserParams.Mode = ee;
        }

        private void TreeViewNodeClick()
        {
            //alert 要防止重复点击相同的  重复读取数据库
            if (selectedMenu == null)
                return;

            ConfigDataGridTop();
            uCPagePanel1.Init(selectedMenu.UserParams);
            BeginBindData();
        }

        private void ConfigDataGridTop()
        {
            if (selectedMenu == null)
            {
                buttonNew.IsEnabled = false;
                expanderMore.IsEnabled = false;
                return;
            }
            expanderMore.IsEnabled = true;

            //button_print.IsEnabled = selectedMenu.CanPrint;
            //button_import.IsEnabled = selectedMenu.CanImport;
            buttonNew.IsEnabled = selectedMenu.CanNew;
            if (selectedMenu.NewButtonText != string.Empty)
                buttonNew.Content = selectedMenu.NewButtonText;
            else
                buttonNew.Content = "创建";


            //分组数据
            if (DoubleHConfig.UserConfig.GroupData)
            {
                canvasGroup.Visibility = Visibility.Visible;
                labelIndex1.Content = "00001";
                labelIndex2.Content = DoubleHConfig.UserConfig.GroupDataCount.ToString("D5");
            }
            else
                canvasGroup.Visibility = Visibility.Collapsed;
        }

        //private void EventImport()
        //{
        //    FCNS.Data.Interface.DataIO io = null;
        //    switch (selectedMenu.TableText)
        //    {
        //        case DataTableText.客户:
        //            break;
        //        default:
        //            MessageWindow.Show("当前类别不支持数据导入");
        //            break;
        //    }
        //    if (io != null)
        //        io.Import(string.Empty);
        //}

        /// <summary>
        /// 如果系统日期被更改了，就自动注销系统。
        /// </summary>
        private void InitCheckDateIsChangedEvent()
        {
            Microsoft.Win32.SystemEvents.TimeChanged += (ss, ee) =>
                {
                    if (DateTime.Now.Date != Table.SysConfig.SysConfigParams.LastLoginDate.Date)
                        LoginOff();
                };
        }

        #region CPU event

        void CPU_ShenHeTableObject(FCNS.Data.Interface.IDataTable table)
        {
            if (table.TableName != selectedMenu.TableName)
                return;
            //switch (table.TableName)
            //{
            //    case "WuLiuS":
            //        WuLiu(table as Table.StoreOrderS);
            //        break;

            //}
            BeginBindData();
        }

        void CPU_InsertTableObject(FCNS.Data.Interface.IDataTable table)
        {
            if (table.TableName != selectedMenu.TableName)
                return;
            BeginBindData();
        }

        //void CPU_DeleteTableObject(FCNS.Data.Interface.IDataTable table)
        //{
        //    Debug.Assert(uCPagePanel1.Items != null);
        //        ((IList)uCPagePanel1.Items).Remove(table);
        //}

        void CPU_ReloadTableList(FCNS.Data.Interface.IDataTable table)
        {
            if (table.TableName != selectedMenu.TableName)
                return;
            BeginBindData();
        }

        private void WuLiu(Table.StoreOrderS order)
        {
            if (Table.SysConfig.SysConfigParams.UseWuLiuS && Table.UserS.LoginUser.GetAuthority(DataTableText.仓库物流跟踪) > Table.UserS.EnumAuthority.查看)
            {
                if (order.Flag == Table.StoreOrderS.EnumFlag.出入库单 && order.ChuKu)
                    pluginManager.LoadPlugin("WuLiuS.dll", null, DataTableText.仓库物流跟踪, null, order.OrderNO);
            }
        }
        #endregion



        private void ThisClose()
        {
            pluginManager.UnloadAllExtension();
            ConfigSerializer.SaveConfig(DoubleHConfig.UserConfig, Table.UserS.LoginUser.Id);
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            PrintFunction.Dispose();
        }
    
    
    ////公共
    //    /// <summary>
    //    /// 添加菜单
    //    /// </summary>
    //    public void AddItemToExpanderMenu(Button btn)
    //    {
    //        MessageBox.Show((expanderConfig.Content is Grid).ToString());
    //    }
    }
}
